// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;

namespace SnapObjects.Data
{
    internal class ColumnElement : SqlElement
    {
        public ColumnElement(string columnName, string alias)
            : this(columnName, alias, null, SqlRightType.Clause)
        {

        }

        public ColumnElement(SqlBuildStatement statement, string alias)
            : this(null, alias, statement, SqlRightType.Statement)
        {

        }

        public ColumnElement(
            string columnName, string alias, object value, SqlRightType valueType)
            : base(String.IsNullOrWhiteSpace(alias) ? columnName : alias)
        {
            if (columnName.IndexOf('.') > 0)
            {
                var arr = columnName.Split('.');

                this.ColumnName = arr[arr.Length - 1];
                this.Table = arr[arr.Length - 2];

                if (arr.Length > 2)
                {
                    var schema = String.Empty;

                    for (int i = 0; i < arr.Length - 2; i++)
                    {
                        schema = String.IsNullOrWhiteSpace(schema) ? arr[i] : schema + "." + arr[i];
                    }

                    this.Schema = schema;
                }
            }
            else
            {
                this.ColumnName = columnName;
            }

            this.Alias = alias;
            this.Value = value;
            this.ValueType = valueType;
        }

        public override SqlElementType ElementType => SqlElementType.Column;

        public string Schema { get; private set; }
        public string Table { get; private set; }
        public string ColumnName { get; private set; }
        public string Alias { get; private set; }
        public object Value { get; private set; }
        public SqlRightType ValueType { get; private set; }

        public override SqlElement Clone()
        {
            var value = this.Value;

            if (value is SqlStatement statement)
            {
                value = statement.Clone();
            }

            return new ColumnElement(
                this.ColumnName, this.Alias, value, this.ValueType)
            {
                Table = this.Table
            };
        }
    }
}
